package com.itheima.reggie.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从session对象中获取SESSION_EMPLOYEE
        Employee employee = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        //判断是否为空
        //不为空放行,并将当前登录信息放到holder中
        if (employee != null){
            EmployeeHolder.set(employee);
            return true;
        }else {
            //如果获取不到,返回错误提示
            log.info("用户身份不合法");
            //根据前端响应拦截器要求if (res.data.code === 0 && res.data.msg === 'NOTLOGIN') {// 返回登录页面
            //根据要求进行创建Result对象
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");

            ObjectMapper objectMapper = new ObjectMapper();
            //将ResultInfo对象转成json字符串
            String s = objectMapper.writeValueAsString(resultInfo);
            //通过响应写回
            response.getWriter().write(s);
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //离开服务器的时候，将holder中的信息清除
        EmployeeHolder.remove();
    }
}
